package com.lbd.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.lbd.common.constrant.ProductConstrant;
import com.lbd.common.to.SkuEsModel;
import com.lbd.common.to.SkuHasStockVo;
import com.lbd.common.to.SpuBoundTO;
import com.lbd.common.to.SkuReductionTO;
import com.lbd.common.utils.R;
import com.lbd.gulimall.product.entity.*;
import com.lbd.gulimall.product.feign.CouponFeignService;
import com.lbd.gulimall.product.feign.SearchFeignService;
import com.lbd.gulimall.product.feign.WareFeignService;
import com.lbd.gulimall.product.service.*;
import com.lbd.gulimall.product.vo.spu.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbd.common.utils.PageUtils;
import com.lbd.common.utils.Query;

import com.lbd.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;
    @Autowired
    private SpuInfoService spuInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增商品
     * TODO: 失败逻辑的处理
     *
     * @param spuInfo: 新增商品VO
     * @return:
     * @author: linbd
     * @date: 2021/6/24 14:43
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO spuInfo) {
        //1. 保存spu基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2. 保存spu描述信息  pms_spu_info_desc
        Long spuId = spuInfoEntity.getId();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", spuInfo.getDecript()));
        spuInfoDescService.save(spuInfoDescEntity);
        //3. 保存spu图片信息  pms_spu_images
        List<String> images = spuInfo.getImages();
        List<SpuImagesEntity> spuImagesEntities = images.stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setImgUrl(image);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntities);
        //4. 保存spu规格参数信息  pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(attr, productAttrValueEntity);
            productAttrValueEntity.setSpuId(spuId);
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            if (attrEntity != null) {
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            }
            productAttrValueEntity.setAttrSort(0);
            productAttrValueEntity.setQuickShow(1);
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);
        //5. 保存积分信息 sms_spu_bounds(远程)
        Bounds bounds = spuInfo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(spuId);
        R r1 = couponFeignService.save(spuBoundTO);
        if (r1.getCode() != 0) {
            log.error("远程积分服务调用失败");
        }
        //6. 保存spu对应的sku的信息
        List<Skus> skus = spuInfo.getSkus();
        skus.stream().forEach(sku -> {
            //6.1 保存sku的基本信息    pms_sku_info
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setBrandId(spuInfo.getBrandId());
            skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
            skuInfoEntity.setSpuId(spuId);
            List<Images> skuImages1 = sku.getImages();
            skuImages1.forEach(images1 -> {
                if (images1.getDefaultImg() == 1) {
                    skuInfoEntity.setSkuDefaultImg(images1.getImgUrl());
                }
            });
            skuInfoService.save(skuInfoEntity);
            Long skuId = skuInfoEntity.getSkuId();
            //6.2 保存sku的图片信息    pms_sku_images
            List<Images> skuImages = sku.getImages();
            List<SkuImagesEntity> skuImagesEntities = skuImages.stream().map(skuImage -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                BeanUtils.copyProperties(skuImage, skuImagesEntity);
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgSort(0);
                return skuImagesEntity;
            }).filter(skuImage -> !StringUtils.isEmpty(skuImage.getImgUrl())).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);
            //6.3 保存sku关联的优惠/满减/会员价格信息  sms_sku_full_reduction，sms_sku_ladder，sms_member_price(远程)
            SkuReductionTO spuReductionTO = new SkuReductionTO();
            BeanUtils.copyProperties(sku, spuReductionTO);
            spuReductionTO.setSkuId(skuId);
            if (spuReductionTO.getFullCount() > 0 || spuReductionTO.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                R r2 = couponFeignService.saveFullreduction(spuReductionTO);
                if (r2.getCode() != 0) {
                    log.error("远程优惠服务调用失败");
                }
            }
            //6.4 保存sku的销售属性    pms_sku_sale_attr_value
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setAttrSort(0);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
        });
    }

    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String publishStatus = (String) params.get("status");
        if (!StringUtils.isEmpty(publishStatus)) {
            wrapper.eq("publish_status", publishStatus);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //根据spu查询sku
        QueryWrapper<SkuInfoEntity> skuInfoEntityWrapper = new QueryWrapper();
        skuInfoEntityWrapper.eq("spu_id", spuId);
        List<SkuInfoEntity> skus = skuInfoService.list(skuInfoEntityWrapper);

        //调用仓储微服务。这里涉及远程调用，对网络资源开销大，因此在循环外步骤只执行一次，存入map内存。通过skuId来获取各自是否有库存
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
        };
        Map<Long, Boolean> result = null;
        try {
            R r = wareFeignService.hasStock(skuIds);
            result = r.getData(typeReference).stream()
                    .collect(Collectors.toMap(key -> key.getSkuId(), value -> value.getHasStock()));
        } catch (Exception e) {
            log.error("调用仓储微服务异常 {}", e);
        }

        //todo:pms_product_attr_value存的是销售属性还是基本属性
        //sku的Attr在同个spu下是一致的，放在循环外只做一次即可
        QueryWrapper<ProductAttrValueEntity> productAttrValueEntityQueryWrapper = new QueryWrapper();
        productAttrValueEntityQueryWrapper.eq("spu_id", spuId);
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(productAttrValueEntityQueryWrapper);
        //根据商品属性关联表的attrId，查出对应的attr信息。并过滤掉不可检索的attr
        List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchIds = attrService.selectByIds(attrIds, 1);
        Set<Long> searchSet = new HashSet<>(searchIds);
        List<SkuEsModel.Attr> attrs = productAttrValueEntities.stream()
                .filter(skuSaleAttrValue -> searchSet.contains(skuSaleAttrValue.getAttrId()))
                .map(skuSaleAttrValue -> {
                    SkuEsModel.Attr attr = new SkuEsModel.Attr();
                    BeanUtils.copyProperties(skuSaleAttrValue, attr);
                    return attr;
                })
                .collect(Collectors.toList());

        //封装ES传输对象
        Map<Long, Boolean> finalResult = result;
        List<SkuEsModel> skuEsModels = skus.stream().map(sku -> {
            SkuEsModel model = new SkuEsModel();
            BeanUtils.copyProperties(sku, model);
            model.setSkuPrice(sku.getPrice());
            model.setSkuImg(sku.getSkuDefaultImg());
            model.setHasStock(finalResult == null ? true : finalResult.get(model.getSkuId()));
            model.setHotScore(0l);
            BrandEntity brandEntity = brandService.getById(model.getBrandId());
            model.setBrandName(brandEntity.getName());
            model.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(model.getCatalogId());
            model.setCatalogName(categoryEntity.getName());
            //查询当前sku下可检索的属性
            model.setAttrs(attrs);
            return model;
        }).collect(Collectors.toList());

        //将数据索引到ES
        R r = searchFeignService.bulkIndexSkuModel(skuEsModels);
        if (r.getCode() == 0) {
            //修改spu_info的上架状态
            spuInfoService.updatePublishStatus(spuId, ProductConstrant.SpuStatusEnum.SPU_UP.getCode());
        } else {
            log.error("远程调用/search/save/product接口发生异常。开始重试...");
            //openfeign的失败重试机制
            /*while(true) {
                try{
                    executeAndDecode(template) //真正执行的方法
                }catch() {
                    try{
                        retryer.continueOrPropagate(e);   //远程调用发现异常，调用重试器的重试方法
                    }catch() {
                        throw ex;
                    }
                    continue;
                }
            }*/
        }
    }

    @Override
    public void updatePublishStatus(Long spuId, Integer publishStatus) {
        baseMapper.updatePublishStatus(spuId, publishStatus);
    }

    @Override
    public BigDecimal getWeight(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        Long spuId = skuInfo.getSpuId();
        SpuInfoEntity spuInfo = this.getById(spuId);
        return spuInfo.getWeight();
    }

}